
const request = axios.create({
    baseURL: requestBaseUrl,
    timeout: 10000
});

const crmRequest = axios.create({
    baseURL: crmRequestBaseUrl,
    timeout: 10000
});

request.interceptors.request.use(config => {
    //config.headers['Authorization'] = sessionStorage.getItem('Admin-Token');
    return config;
},err => {
    return Promise.reject(err);
})

request.interceptors.response.use(res => {
    if (res.status === 500) {
        vm.$message.error("系统内部错误,请联系管理员")
    }
    if (res.data.hasOwnProperty("code")) {
        if (res.data.code === 406) {
            vm.$message.error("系统内部错误")
        } else if(res.data.code === 405) {
            vm.$message.error("请求方式错误")
        }
    }

    return res.data;
},err => {
    if (err.response.status === 401) {
        vm.$message({
            type: 'warning',
            message: '无权限'
        })
    }
    return Promise.reject(err)
})

function getCookie(name) {
    let cookieArr = document.cookie.split(";");
    for(let i = 0; i < cookieArr.length; i++) {
        let cookiePair = cookieArr[i].split("=");
        if(name === cookiePair[0].trim()) {
            return decodeURIComponent(cookiePair[1]);
        }
    }
    return null;
}

crmRequest.interceptors.request.use(config => {
    config.headers['standing'] = getCookie('token')

    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false

    if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
        const requestObj = {
            url: config.url,
            data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
            time: new Date().getTime()
        }
        const sessionObj = sessionCache.getJSON('sessionObj')
        if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
            sessionCache.setJSON('sessionObj', requestObj)
        } else {
            const s_url = sessionObj.url;                  // 请求地址
            const s_data = sessionObj.data;                // 请求数据
            const s_time = sessionObj.time;                // 请求时间
            const interval = 1000;                         // 间隔时间(ms)，小于此时间视为重复提交
            if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
                const message = '数据正在处理，请勿重复提交';
                console.warn(`[${s_url}]: ` + message)
                return Promise.reject(new Error(message))
            } else {
                sessionCache.setJSON('sessionObj', requestObj)
            }
        }
    }
    return config;
},err => {
    return Promise.reject(err);
})

const errorCode = {
    '401': '认证失败，无法访问系统资源',
    '403': '当前操作没有权限',
    '404': '访问资源不存在',
    'default': '系统未知错误，请反馈给管理员'
}

crmRequest.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401) {
        vm.$message.error("登录过期,请重新登录")
        setTimeout(() => {
            location.href = SOURCE_PATH
        }, 1500);
    } else if (code === 500) {
        vm.$message.error(msg)
        return Promise.reject(new Error(msg))
    } else if (code === 601) {
        vm.$message.warning(msg)
        return Promise.reject('error')
    } else if (code !== 200) {
        vm.$message.error(msg)
        return Promise.reject('error')
    } else {
        return res.data
    }
}, error => {
    console.log('err' + error)
    let { message } = error;
    if (message === "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    vm.$message.error(message)
    return Promise.reject(error)
})

// 验证是否为blob格式
function blobValidate(data) {
    return data.type !== 'application/json'
}

// 通用下载方法
function download(url, params, filename, config) {
    return request.post(url, params, {
       // headers: { 'Content-Type': 'application/json' },
        responseType: 'blob',
        //...config
    }).then(async (data) => {
        const isBlob = blobValidate(data);
        if (isBlob) {
            const blob = new Blob([data])
            saveAs(blob, filename)
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
        }

    }).catch((r) => {
        console.error(r)
    })
}

Vue.prototype.download = download


